package 多线程.多线程同步的5种方法;

import java.util.Date;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 廖述京
 * @date 2017/8/31.
 */
public class ReentrantLock_Bank {
    private int count = 0;//账户余额

    //声明锁类
    private Lock lock = new ReentrantLock();

    //存钱
    public void addMoney(int money) {
        //上锁
        lock.lock();
        try {
            count += money;
            System.out.println(new Date(System.currentTimeMillis()).toLocaleString() + "存进：" + money);
        } finally {
            lock.unlock(); //解锁。警告：必须要解锁，否则会造成死锁(即没钥匙的锁，别人用不了)
        }
    }

    //取钱
    public void subMoney(int money) {
        //上锁
        lock.lock();
        try {
            if (count - money < 0) {
                System.out.println("余额不足");
                return;
            }
            count -= money;
            System.out.println(new Date(System.currentTimeMillis()).toLocaleString() + "取出：" + money);
        } finally {
            lock.unlock();//解锁。警告：必须要解锁，否则会造成死锁
        }
    }

    //查询
    public void lookMoney() {
        System.out.println("账户余额：" + count);
    }
}
